<template>
	<div class="publish">
		<div class="head">
			发布
		</div>

		<van-field v-model="publishlist.title" label="文本" placeholder="标题" />

		<van-field v-model="publishlist.content" label="内容" placeholder="标题" />

		<van-field readonly clickable name="picker" :value="publishlist.cate_name" label="选择分类" placeholder="点击选择"
			@click="showPicker = true" />
		<van-popup v-model="showPicker" position="bottom">
			<van-picker show-toolbar :columns="cateList" value-key="name" @confirm="onConfirm"
				@cancel="showPicker = false" />
		</van-popup>

		<van-uploader v-model="fileList" :max-count="3" multiple />

		<div class="head" @click="publish">
			发布
		</div>
	</div>
</template>

<script>
	import {
		mapState
	} from 'vuex';
	import {
		add_article
	} from '@/api/publish'
	import {
		uploadFile
	} from '@/api/upload'
	export default {
		name: 'PublishView',
		data() {
			return {
				publishlist: {
					title: '',
					content: '',
					cate_id: '',
					cate_name: '',
					author: '',
					author_id: '',
					imageSrc: [],
				},
				fileList: [],
				showPicker: false,
			}
		},
		computed: {
			...mapState('CATE', ['cateList']),
			...mapState('UESR', ['uid', 'userInfo'])
		},
		methods: {
			async publish() {
				let {
					uid,
					userInfo,
					publishlist,
					fileList
				} = this;
				if (!uid) {
					this.$toast('请先登录');
					setTimeout(() => {
						this.$router.push('/login')
					}, 300);
					return
				}
				publishlist.author = userInfo.nickname;
				publishlist.author_id = uid


				if (fileList.length == 2) {
					this.$toast('请上传一张或三张')
					return
				}

				if (fileList.length > 0) {
					//上传到服务器
					let task = fileList.map((v, k) => {
						return uploadFile(fileList[k].file)
					})

					publishlist.imageSrc = await Promise.all(task);
				}

				add_article(publishlist).then((res) => {
					console.log(res)
				})
			},
			// onConfirm 分类确认时
			onConfirm({
				name,
				_id
			}) {
				this.showPicker = false;
				this.publishlist.cate_id = _id
				this.publishlist.cate_name = name
			},
		},
	}
</script>

<style>
	.van-cell {
		margin: 10px 0;
	}

	.van-picker__columns {
		/* flex: 0; */
		/* height: 60px; */
	}

	.publish {
		background-color: #f7f7f7;
		height: 100vh;
	}

	.publish .head {
		text-align: center;
		height: 40px;
		line-height: 40px;
		background-color: #e54b43;
		color: #fff;
	}
</style>
